package com.lagou.firstStageFourthModel.Fourth;

import java.io.IOException;
import java.net.Socket;
import java.util.Scanner;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

public class ClientTest {
    public static void main(String[] args) {
        Socket s = null;
        Scanner sc = null;
        ObjectInputStream ois = null;
        ObjectOutputStream oos = null;

        try {
            while (true) {
                // 创建Socket类型的对象并提供服务器的主机名和端口号
                s = new Socket("127.0.0.1", 8888);
                System.out.println("连接服务器成功!");

                // 使用输入输出流通信
                sc = new Scanner(System.in);
                oos = new ObjectOutputStream(s.getOutputStream());
                ois = new ObjectInputStream(s.getInputStream());

                System.out.println("请输入内容账号和密码：");
                String userName = sc.next();
                String password = sc.next();

                UserMessage um1 = new UserMessage("check", new User(userName, password));

                // 客户端向服务器发送UserMessage对象
                oos.writeObject(um1);
                System.out.println("客户端发送数据成功!");

                // 接收服务器返回内容
                Object obj = ois.readObject();

                if (obj instanceof UserMessage) {
                    UserMessage um2 = (UserMessage) obj;
                    String type = um2.getType();

                    if ("success".equals(type)) {
                        System.out.println("登录成功!");
                        break;
                    } else if ("fail".equals(type)) {
                        System.out.println("登录失败!");
                    }
                }
            }
        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
        } finally {
            // 关闭并释放有关资源
            if (null != ois) {
                try {
                    ois.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            if (null != oos) {
                try {
                    oos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            if (null != sc) {
                sc.close();
            }

            if (null != s) {
                try {
                    s.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
